<template>
	<view class="containerbox bgc-white">
		<uv-navbar title="选择课程" auto-back placeholder />
		
		<template v-if="!loading && flowlist.length">
			<scroll-view scrollY class="containerbox">
				<view class="boxs">
					<!-- <view class="items" @click="handleDetail(item)" v-for="item,index in flowlist">{{item.name}}</view> -->
					<view class="items" @click="handleDetail(item, index)" :class="{actived: courseIndex === index}" v-for="item,index in flowlist">{{item.name}}</view>
				</view>
			</scroll-view>
			<view class="flex items-center justify-between bottombox">
				<view class="btn bgc-primary" @click="begin">确认选择</view>
			</view>
		</template>
		
		
		<dw_default :src="`${imageBaseUrl2}/svg/empty.svg`" v-if="!loading && !flowlist.length" class="m-auto" label="暂未开通相关课程~" />
	</view>
</template>

<script setup>
	
import { ref } from 'vue';
import { onLoad } from "@dcloudio/uni-app";
import { appointment } from '@/common/apis/study';
import { getCourseList_api, postExerJoin_api } from '@/common/apis/course';
import {imageBaseUrl2} from "@/common/config";


const userId = ref(0);
const appointmentId = ref(0);
const appointmentInfo = ref(0);


/** 请求状态 */
const loading = ref(true);


const getAppointInfo = async () => {
	const result = await appointment({ id: appointmentId.value, userId: userId.value });
	appointmentInfo.value = result;
};

onLoad(async options => {
	appointmentId.value = options.appointmentId;
	userId.value = options.userId || 0;
	initEvent()
	appointmentId.value && userId.value && await getAppointInfo();
	if (appointmentInfo.value?.course?.id) {
		const findIndex = flowlist.value.findIndex(item => item.id === appointmentInfo.value?.course?.id);
		if (!!~findIndex) {
			courseIndex.value = findIndex;
			courseId.value = appointmentInfo.value?.course?.id;
		};
	};
}) 

const flowlist = ref([])
async function initEvent(){
	flowlist.value = await getCourseList_api({categoryId: 4})
	loading.value = false;
}

const courseId = ref()
const courseIndex = ref()
async function handleDetail({id}, index){
	courseId.value = id
	courseIndex.value = index
}

async function begin(){
	if(courseIndex.value >= 0){
		let res = await postExerJoin_api({courseId: courseId.value, appointmentId: appointmentId.value, userId: userId.value });
		uni.$fui.href(`/pages/course/reading/rank?itemId=${res.id}&courseId=${courseId.value}&userId=${userId.value}`)
	} else{
		uni.showToast({
			title: '请选择课程',
			icon: 'none'
		})
	}
}
</script>

<style lang="scss" scoped>
.boxs{display: grid; grid-template-columns: 1fr 1fr; gap: 20rpx; padding: 32rpx 32rpx;}
.items{background-color: #f6f6f6; font-size: 28rpx; height: 120rpx; border-radius: 12rpx; display: flex; align-items: center; justify-content: center;padding: 0 10rpx;text-align: center}
.actived{background-color: #f69b2c; color: #fff;}
.bottombox{padding: 20rpx 32rpx;}
.btn{height: 80rpx; border-radius: 12rpx; flex: 1; text-align: center; line-height: 80rpx; color: #fff; font-size: 28rpx;}
</style>